package com.shitou.springai1.user.controller;

import com.shitou.springai1.admin.entity.dto.UserDto;
import com.shitou.springai1.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 当前登录用户控制器
 * 提供获取当前登录用户信息的API接口
 */
@RestController
@RequestMapping("/api/user")
public class CurrentUserController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前登录用户信息
     * @return 用户信息，包括学号/工号、昵称、头像等
     */
    @GetMapping("/current")
    public Map<String, Object> getCurrentUserInfo() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 从Spring Security获取当前登录用户的认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.isAuthenticated() &&
                    !"anonymousUser".equals(authentication.getPrincipal())) {

                // 获取学号/工号作为用户名
                String username = authentication.getName();

                // 根据学号/工号查询用户信息
                UserDto userDto = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserDto>()
                        .eq("stu_or_tea_id", username));

                if (userDto != null) {
                    // 构建返回的用户信息
                    result.put("success", true);
                    result.put("stuOrTeaId", userDto.getStuOrTeaId());
                    result.put("nickName", userDto.getNickName());
                    result.put("imageUrl", userDto.getImageUrl() != null ? userDto.getImageUrl() : "/logo/avatar.png");
                    result.put("userId", userDto.getId());
                } else {
                    result.put("success", false);
                    result.put("message", "用户信息不存在");
                }
            } else {
                result.put("success", false);
                result.put("message", "未登录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取用户信息失败：" + e.getMessage());
        }
        return result;
    }
}
